package com.example.testapp.activity.activity.study;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Xml;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.testapp.R;
import com.example.testapp.activity.activity.SuperActivity;
import com.example.testapp.activity.adapter.BolgCommentAdapter;
import com.example.testapp.activity.http.AsyncHttpUtil;
import com.example.testapp.activity.http.Contacts;
import com.example.testapp.activity.model.BolgComment;
import com.example.testapp.activity.view.ErrorHintView;
import com.example.testapp.activity.view.listview.PullToRefreshAdapterViewBase;
import com.example.testapp.activity.view.listview.PullToRefreshBase;
import com.example.testapp.activity.view.listview.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 博客评论
 * Created by l on 2016/11/17.
 */

public class BlogsCommentActivity extends SuperActivity {

    private PullToRefreshListView mListView;
    private ErrorHintView   mHintView;
    private TextView   mTitle;

    private List<BolgComment> bolgList = new ArrayList<>();
    private BolgCommentAdapter mAdapter;

    private int pageNext = 1;	//下一页页码
    private boolean flag = false;
    private String id;
    private LinearLayout footerView;    //最后一条listview

    public static int VIEW_LIST = 1;
    /**显示断网**/
    public static int VIEW_WIFIFAILUER = 2;
    /** 显示加载数据失败 **/
    public static int VIEW_LOADFAILURE = 3;
    public static int VIEW_LOADING = 4;
    public static int VIEW_NODATA = 5;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_blogs_comment);
        getWindow().setBackgroundDrawable(null);
        initLayout();
    }

    private void initLayout() {
        RelativeLayout headView = (RelativeLayout) this.findViewById(R.id.head);
        headView.findViewById(R.id.back_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTitle = (TextView) headView.findViewById(R.id.head_title);
        mListView = (PullToRefreshListView) this.findViewById(R.id.blogs_list);
        mHintView = (ErrorHintView) this.findViewById(R.id.blogs_hintView);

        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        String title = intent.getStringExtra("title");
        mTitle.setText(title);

        showViewLoading(VIEW_LOADING);
        setUpPullToList();
        loadBolgCommentInfo(true);
    }

    private void showViewLoading(int i) {
        mHintView.setVisibility(View.GONE);
        mListView.setVisibility(View.GONE);

        switch (i){
            case 1:
                mHintView.hideLoading();
                mListView.setVisibility(View.VISIBLE);
                break;
            case 2:
                mHintView.hideLoading();
                mHintView.netError(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {
                        pageNext = 1;
                        flag = false;
                        showViewLoading(VIEW_LOADING);
                        loadBolgCommentInfo(true);
                    }
                });
                break;
            case 3:
                mHintView.hideLoading();
                mHintView.loadFailure(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {
                        pageNext = 1;
                        flag = false;
                        showViewLoading(VIEW_LOADING);
                        loadBolgCommentInfo(true);
                    }
                });
                break;
            case 4:
                mHintView.loadingdata();
                break;
            case 5:
                mHintView.hideLoading();
                mHintView.noData();
                break;
        }
    }

    private void setUpPullToList() {
       mAdapter = new BolgCommentAdapter(mContext, bolgList);
       mListView.setAdapter(mAdapter);
       mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
           @Override
           public void onRefresh(PullToRefreshBase<ListView> refreshView) {
               if (refreshView.isHeaderShown()){
                   pageNext = 1;
                   flag = false;
                   loadBolgCommentInfo(true);
               }
           }
       });
       mListView.setOnPreRefreshingAnimListener(new PullToRefreshAdapterViewBase.OnPreRefreshingAnimListener() {
           @Override
           public void onPreRefreshingAnim() {
               mListView.setFooterLoadingViewHeaderText("加载更多评论");
           }
       });
       mListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
           @Override
           public void onLastItemVisible() {
               if (pageNext == 0){
                   mListView.onRefreshComplete();
                   if (footerView == null){
                       footerView = (LinearLayout) View.inflate(mContext, R.layout.item_pull_to_refresh_footer, null);
                       TextView  footer = (TextView) footerView.findViewById(R.id.footer);
                       footer.setText("到底了呢-共" + bolgList.size() + "条评论");
                       mListView.getRefreshableView().addFooterView(footerView);
                   }
               }else{
                   //滑动到底部自动刷新
                   flag = false;
                   loadBolgCommentInfo(false);
               }
           }
       });
    }

    private List<BolgComment> comments = new ArrayList<>();
    /**
     * 加载评论内容
     * @param clean
     */
    private void loadBolgCommentInfo(final boolean clean) {
        String url = Contacts.STR_BEFORE + id + Contacts.STR_AFTER + pageNext + "/20";
        AsyncHttpUtil.get(url, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                 if (footerView != null){
                     mListView.getRefreshableView().removeFooterView(footerView);
                     footerView = null;
                 }
                 mListView.onRefreshComplete();
                 if (responseBody != null && responseBody.length > 0){
                       try {
                           if (clean){
                               bolgList.clear();
                           }
                           comments.clear();
                           ByteArrayInputStream bis = new ByteArrayInputStream(responseBody);
                           parseCommentXml(bis);
                           if (comments.size() == 0 && comments.size() < 20){
                               pageNext = 0;
                           }else{
                               pageNext++;
                           }
                           bolgList.addAll(comments);
                           if (bolgList.size() == 0){
                               showViewLoading(VIEW_NODATA);
                           }else{
                               showViewLoading(VIEW_LIST);
                               mAdapter.notifyDataSetChanged();
                           }
                       }catch (Exception e){
                           e.printStackTrace();
                           showViewLoading(VIEW_LOADFAILURE);
                       }
                 }else{
                     showViewLoading(VIEW_LOADFAILURE);
                 }
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                  showViewLoading(VIEW_WIFIFAILUER);
            }
        });
    }

    /**
     * 解析评论内容
     *
     * @param bis
     * @throws XmlPullParserException
     * @throws IOException
     */
    private void parseCommentXml(InputStream bis) throws XmlPullParserException, IOException {
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(bis, "UTF-8");
        int event =  parser.getEventType();
        BolgComment item = null;

        while (event != XmlPullParser.END_DOCUMENT){
            switch (event){
                case XmlPullParser.START_DOCUMENT:
                    break;
                case XmlPullParser.START_TAG:
                    if ("entry".equals(parser.getName())){
                        flag = true;
                        item = new BolgComment();
                    }
                    if (flag){
                        if ("id".equals(parser.getName())){
                            String id = parser.nextText();
                            item.setId(id);
                        }else if ("title".equals(parser.getName())){
                            String title = parser.nextText();
                            item.setTitle(title);
                        }else if ("published".equals(parser.getName())){
                            String published = parser.nextText();
                            item.setPublished(published);
                        }else if ("updated".equals(parser.getName())){
                            String updated = parser.nextText();
                            item.setUpdated(updated);
                        }else if ("author".equals(parser.getName())){

                        }else if ("name".equals(parser.getName())){
                            String name = parser.nextText();
                            item.setName(name);
                        }else if ("uri".equals(parser.getName())){
                            String uri = parser.nextText();
                            item.setUri(uri);
                        }else if ("content".equals(parser.getName())){
                            String content = parser.nextText();
                            item.setContent(content);
                        }
                    }
                    break;
                case XmlPullParser.TEXT:
                    break;
                case XmlPullParser.END_TAG:
                    if ("entry".equals(parser.getName())){
                        comments.add(item);
                    }
                    break;
            }
            event = parser.next();
        }
    }

    @Override
    protected void obtainInfo() {

    }
}
